import logging
from typing import Dict, Any, Optional

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


class APIError(Exception):
    """
    自定义API错误基类
    """
    def __init__(self, message: str, http_status: int = 500, error_code: str = "INTERNAL_ERROR"):
        self.message = message
        self.http_status = http_status
        self.error_code = error_code
        super().__init__(self.message)


class NotFoundError(APIError):
    """
    资源未找到错误 (404)
    """
    def __init__(self, message: str = "Resource not found"):
        super().__init__(message, http_status=404, error_code="NOT_FOUND")


class BadRequestError(APIError):
    """
    请求参数错误 (400)
    """
    def __init__(self, message: str = "Invalid request parameters"):
        super().__init__(message, http_status=400, error_code="BAD_REQUEST")


class UnauthorizedError(APIError):
    """
    未授权错误 (401)
    """
    def __init__(self, message: str = "Unauthorized access"):
        super().__init__(message, http_status=401, error_code="UNAUTHORIZED")


class ForbiddenError(APIError):
    """
    权限禁止错误 (403)
    """
    def __init__(self, message: str = "Access forbidden"):
        super().__init__(message, http_status=403, error_code="FORBIDDEN")


class InternalServerError(APIError):
    """
    服务器内部错误 (500)
    """
    def __init__(self, message: str = "Internal server error"):
        super().__init__(message, http_status=500, error_code="INTERNAL_ERROR")


class ServiceUnavailableError(APIError):
    """
    服务不可用错误 (503)
    """
    def __init__(self, message: str = "Service unavailable"):
        super().__init__(message, http_status=503, error_code="SERVICE_UNAVAILABLE")


class RateLimitError(APIError):
    """
    请求频率限制错误 (429)
    """
    def __init__(self, message: str = "Rate limit exceeded", retry_after: int = 60):
        self.retry_after = retry_after
        super().__init__(message, http_status=429, error_code="RATE_LIMIT_EXCEEDED")


class TranslationError(APIError):
    """
    翻译服务错误
    """
    def __init__(self, message: str = "Translation service error"):
        super().__init__(message, http_status=500, error_code="TRANSLATION_ERROR")


class InsufficientPointsError(APIError):
    """
    积分不足错误
    """
    def __init__(self, message: str = "Insufficient points"):
        super().__init__(message, http_status=400, error_code="INSUFFICIENT_POINTS")


class ErrorHandler:
    """
    错误处理工具类
    提供统一的错误响应格式和处理方法
    """
    
    @staticmethod
    def create_error_response(
        is_success: int,
        message: str,
        shopify_domain: str,
        error_code: Optional[str] = None,
        metadata_model: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        创建统一格式的错误响应
        
        Args:
            is_success: 操作是否成功 (0=失败, 1=成功)
            message: 错误消息
            shopify_domain: 店铺域名
            error_code: 错误代码
            metadata_modle: 元数据模块
            
        Returns:
            Dict[str, Any]: 格式化的错误响应
        """
        response = {
            "is_success": is_success,
            "message": message,
            "shopify_domain": shopify_domain,
            "data": {}
        }
        
        # 添加错误代码（如果提供）
        if error_code:
            response["data"]["error_code"] = error_code
        
        # 添加元数据模块（如果提供）
        if metadata_model:
            response["data"]["metadata_model"] = metadata_model
        
        # 注意：根据要求，错误响应中不包含积分计算结果和长度信息
        
        return response
    
    @staticmethod
    def handle_api_error(error: APIError, shopify_domain: str = "", metadata_model: Optional[str] = None) -> Dict[str, Any]:
        """
        处理API错误
        
        Args:
            error: APIError实例
            shopify_domain: 店铺域名
            metadata_modle: 元数据模块
            
        Returns:
            Dict[str, Any]: 格式化的错误响应
        """
        logging.error(f"API错误 - 代码: {error.error_code}, 消息: {error.message}")
        return ErrorHandler.create_error_response(
            is_success=0,
            message=error.message,
            shopify_domain=shopify_domain,
            error_code=error.error_code,
            metadata_model=metadata_model
        )
    
    @staticmethod
    def handle_generic_exception(exception: Exception, shopify_domain: str = "", metadata_model: Optional[str] = None) -> Dict[str, Any]:
        """
        处理通用异常
        
        Args:
            exception: 异常实例
            shopify_domain: 店铺域名
            metadata_modle: 元数据模块
            
        Returns:
            Dict[str, Any]: 格式化的错误响应
        """
        # 增强异常日志，包含异常类型、消息和堆栈信息
        logging.error(f"未预期的异常 - 店铺域名: {shopify_domain}, 异常类型: {type(exception).__name__}, 异常消息: {str(exception)}", exc_info=True)
        
        # 为了安全，不向客户端暴露详细的异常信息
        error = InternalServerError("An unexpected error occurred")
        return ErrorHandler.handle_api_error(error, shopify_domain, metadata_model)